package wf.source.hrm.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;
import wf.source.hrm.client.RedisClient;
import wf.source.hrm.service.IImageValidateCodeService;
import wf.source.hrm.util.VerifyCodeUtils;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片验证实现类
 */
@Service
public class ImageValidateCodeServiceImpl implements IImageValidateCodeService {
    @Autowired
    private RedisClient redisClient;
    @Override
    public String generateImgCode(String key) {
        //使用工具类产生4位随机的字符
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //把4位随机字符写入redis
        Map<String,Object> params=new HashMap<>();
        params.put("key",key);
        params.put("value",code);
        //有效期60秒 即1分钟
        params.put("expire",60);
        redisClient.add(params);

        //生成图片 加密返回
        BASE64Encoder encoder=new BASE64Encoder();
        //字节数组输出流
        ByteArrayOutputStream data=new ByteArrayOutputStream();
        //工具类输出图片
        VerifyCodeUtils.outputImage(100,30,data,code);
        //把数据 转换为字节数组 返回

        return encoder.encode(data.toByteArray());
    }
}
